#!/bin/bash
# This is a simple build script and will be executed on your CI system if 
# available.  Otherwise it will execute while your application is stopped
# before the deploy step.  This script gets executed directly, so it
# could be python, php, ruby, etc. 

set -e



#
# The PHP dir most be controlled by Drupal content
#
if [ -e "${OPENSHIFT_REPO_DIR}php" -a ! -h "${OPENSHIFT_REPO_DIR}php" ]
then
  echo "ERROR: The 'php' directory in your Git repo prevents Drupal from being installed.  Please remove 'php' and push again."
  exit 5
fi


DRUPAL_DIR=${OPENSHIFT_DATA_DIR}drupal
DRUPAL_SITE_DIR=${OPENSHIFT_DATA_DIR}sites

echo

# Drush settings
cat >$OPENSHIFT_HOMEDIR/.drush/drushrc.php <<EOF
<?php
  \$options['uri'] = \$_ENV['OPENSHIFT_APP_DNS'];
  \$options['root'] = \$_ENV['OPENSHIFT_REPO_DIR'].'php';
EOF

#
# If there is no current download of Drupal, create one.
#
if [ ! -d "${OPENSHIFT_DATA_DIR}downloads/current" ]
then
  mkdir -p ${OPENSHIFT_TMP_DIR}drupal

  echo "Download and install the latest stable version of Drupal"
  echo

  mkdir -p ${OPENSHIFT_DATA_DIR}downloads
  if ! drush dl drupal --destination=${OPENSHIFT_DATA_DIR}downloads --yes
  then
    echo "ERROR: Unable download and install Drupal."
    exit 7
  fi

  #
  # Link the /current symlink to the latest Drupal instance
  #
  rm -f ${OPENSHIFT_DATA_DIR}downloads/current
  LATEST=$(ls -1t ${OPENSHIFT_DATA_DIR}downloads | head -1)
  export DRUPAL_INSTALL_DIR="${OPENSHIFT_DATA_DIR}downloads/${LATEST}"
  ln -s ${LATEST} ${OPENSHIFT_DATA_DIR}downloads/current

  mv $DRUPAL_INSTALL_DIR/sites $DRUPAL_INSTALL_DIR/sites.original

  #
  # Ensure there is a default health check
  #
  cp ${OPENSHIFT_REPO_DIR}.openshift/health_check.php ${DRUPAL_INSTALL_DIR}

  patch ${DRUPAL_INSTALL_DIR}/.htaccess < ${OPENSHIFT_REPO_DIR}.openshift/.htaccess.patch

  echo "Drupal installed to $DRUPAL_INSTALL_DIR"
else
  DRUPAL_INSTALL_DIR=$(readlink -f ${OPENSHIFT_DATA_DIR}downloads/current)
  echo "Drupal is already installed at $DRUPAL_INSTALL_DIR"
fi

echo

#
# Link the /sites directory (where Drupal stores modules and files)
# into the install dir in order to keep it easily accessible.
#/
if [ ! -d "$DRUPAL_SITE_DIR" ]
then
  cp -r $DRUPAL_INSTALL_DIR/sites.original $DRUPAL_SITE_DIR
  ln -sfn ../../sites $DRUPAL_INSTALL_DIR/sites
fi

#
# Ensure that the app-root/runtime/repo/php PHP directory points
# to a valid Drupal instance directory
#
ln -sfn ../../data/downloads/current ${OPENSHIFT_REPO_DIR}php
if [ ! -d "${OPENSHIFT_REPO_DIR}php" ]
then  
  echo "ERROR: Unable to link the PHP directory, as the current Drupal instance is not a valid directory."
  exit 8
fi

if [ ! -f "${OPENSHIFT_REPO_DIR}php/ip.txt" ]; then
  echo "Install  ${OPENSHIFT_REPO_DIR}php/ip.txt"
  touch ${OPENSHIFT_REPO_DIR}php/ip.txt
fi